//
// connection.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef CONNECTION_HPP
#define CONNECTION_HPP

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "request_handler.hpp"
#include "log.h"

/// Represents a single connection from a client.
class Connection
            : public boost::enable_shared_from_this<Connection>,
            private boost::noncopyable
{
public:
    /// Construct a connection with the given io_service.
    explicit Connection(boost::asio::io_service& io_service,
                        request_handler& handler);

    /// Get the socket associated with the connection.
    boost::asio::ip::tcp::socket& socket();

    /// Start the first asynchronous operation for the connection.
    void start();
    
    /// Write outReply to some connection
    void write() ;

private:
    /// Handle completion of a read operation.
    void handle_read_header(const boost::system::error_code& e) ;
    void handle_read_body(const boost::system::error_code& error) ;


    /// Handle completion of a write operation.
    void handle_write(const boost::system::error_code& e);

    /// Strand to ensure the connection's handlers are not called concurrently.
    boost::asio::io_service::strand strand_;

    /// Socket for the connection.
    boost::asio::ip::tcp::socket socket_;

    /// The handler used to process the incoming request.
    request_handler& request_handler_;

    /// The incoming request.
    Message inMsg;

    /// The reply to be sent back to the client.
    Message outReply ;
};

typedef boost::shared_ptr<Connection> ConnectionPtr;

#endif // CONNECTION_HPP
